<?php

namespace Home\Service;
use Home\Common\FIdConst;


class GoodsownerInventoryService extends PSIBaseService {
	
	public function goodsownerList() {
		if($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$sql = "select id,code,name from  t_goodsowner";
		$queryParams = array();
		
		$ds = new DataOrgService();
		$rs = $ds->buildSQL(FIdConst::GOODSOWNER_INVENTORY_INIT, "t_goodsowner");
		if($rs) {
			$sql .= " where " . $rs[0];
			$queryParams = $rs[1];
		}
		
		$sql .= " order by code";
		
		return M()->query($sql,$queryParams);
	}
	
	
	public function inventoryDetailList($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$goodsownerId = $params["goodsownerId"];
		$goodsId = $params["goodsId"];
		$dtFrom = $params["dtFrom"];
		$dtTo = $params["dtTo"];
		$page = $params["page"];
		$start = $params["start"];
		$limit = $params["limit"];
		
		$db = M();
		$sql = "select g.id, g.code, g.name, g.spec, u.name as unit_name,
						v.in_count, v.out_count,v.balance_count,
						v.biz_date,  user.name as biz_user_name, v.ref_number, v.ref_type,
						goodsowner.name as bizgoodsownername
					from t_goodsowner_inventory_detail v, t_goods g, t_goods_unit u, t_user user, t_goodsowner goodsowner
						where v.goodsowner_id = '%s' and v.goods_id = '%s'  
						and goodsowner.id = v.biz_goodsowner_id
						and v.goods_id = g.id and g.unit_id = u.id and v.biz_user_id = user.id " 
					. " limit " . $start . ", " . $limit;
		$data = $db->query($sql, $goodsownerId, $goodsId, $dtFrom, $dtTo);
		
		$result = array();
		
		foreach ( $data as $i => $v ) {
			$result[$i]["goodsId"] = $v["id"];
			$result[$i]["goodsCode"] = $v["code"];
			$result[$i]["goodsName"] = $v["name"];
			$result[$i]["goodsSpec"] = $v["spec"];
			$result[$i]["unitName"] = $v["unit_name"];
			$result[$i]["inCount"] = $v["in_count"];
			$result[$i]["inPrice"] = $v["in_price"];
			$result[$i]["inMoney"] = $v["in_money"];
			$result[$i]["outCount"] = $v["out_count"];
			$result[$i]["outPrice"] = $v["out_price"];
			$result[$i]["outMoney"] = $v["out_money"];
			$result[$i]["balanceCount"] = $v["balance_count"];
			$result[$i]["balancePrice"] = $v["balance_price"];
			$result[$i]["balanceMoney"] = $v["balance_money"];
			$result[$i]["bizDT"] = date("Y-m-d", strtotime($v["biz_date"]));
			$result[$i]["bizUserName"] = $v["biz_user_name"];
			$result[$i]["refNumber"] = $v["ref_number"];
			$result[$i]["refType"] = $v["ref_type"];
			$result[$i]["bizGoodsownerName"] = $v["bizgoodsownername"];
		}
		
		$sql = "select count(*) as cnt from t_inventory_detail" . " where warehouse_id = '%s' and goods_id = '%s' " . "     and (biz_date between '%s' and '%s')";
		$data = $db->query($sql, $warehouseId, $goodsId, $dtFrom, $dtTo);
		
		return array(
				"details" => $result,
				"totalCount" => $data[0]["cnt"]
		);
	}
	
	public function inventoryList($params) {

		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$goodsownerId = $params["goodsownerId"];
		$code = $params["code"];
		$name = $params["name"];
		$spec = $params["spec"];
		$page = $params["page"];
		$start = $params["start"];
		$limit = $params["limit"];
		
		$db = M();
		$queryParams = array();
		$queryParams[] = $goodsownerId;
		
		$sql = "select
					g.id, g.code, g.name, g.spec, u.name as unit_name,
					v.balance_count,v.in_count,v.out_count
				 from t_goodsowner_inventory v, t_goodsowner o, t_goods g, t_goods_unit u
					where v.goodsowner_id = o.id and (v.goods_id = g.id) and (g.unit_id = u.id)
				          and (v.goodsowner_id = '%s')  ";
		if ($code) {
			$sql .= " and (g.code like '%s')";
			$queryParams[] = "%{$code}%";
		}
		if ($name) {
			$sql .= " and (g.name like '%s' or g.py like '%s')";
			$queryParams[] = "%{$name}%";
			$queryParams[] = "%{$name}%";
		}
		if ($spec) {
			$sql .= " and (g.spec like '%s')";
			$queryParams[] = "%{$spec}%";
		}
		$sql .= " order by g.code
				limit %d, %d";
		$queryParams[] = $start;
		$queryParams[] = $limit;
		
		$data = $db->query($sql, $queryParams);
		
		$result = array();
		
		foreach ( $data as $i => $v ) {
			$result[$i]["goodsId"] = $v["id"];
			$result[$i]["goodsCode"] = $v["code"];
			$result[$i]["goodsName"] = $v["name"];
			$result[$i]["goodsSpec"] = $v["spec"];
			$result[$i]["unitName"] = $v["unit_name"];
			$result[$i]["inCount"] = $v["in_count"];
			$result[$i]["inPrice"] = $v["in_price"];
			$result[$i]["inMoney"] = $v["in_money"];
			$result[$i]["outCount"] = $v["out_count"];
			$result[$i]["outPrice"] = $v["out_price"];
			$result[$i]["outMoney"] = $v["out_money"];
			$result[$i]["balanceCount"] = $v["balance_count"];
			$result[$i]["balancePrice"] = $v["balance_price"];
			$result[$i]["balanceMoney"] = $v["balance_money"];
			$result[$i]["afloatCount"] = $v["afloat_count"];
			$result[$i]["afloatPrice"] = $v["afloat_price"];
			$result[$i]["afloatMoney"] = $v["afloat_money"];
		}
		
		$queryParams = array();
		$queryParams[] = $warehouseId;
		$sql = "select count(*) as cnt
				from t_inventory v, t_goods g, t_goods_unit u
				where (v.warehouse_id = '%s') and (v.goods_id = g.id) and (g.unit_id = u.id) ";
		if ($code) {
			$sql .= " and (g.code like '%s')";
			$queryParams[] = "%{$code}%";
		}
		if ($name) {
			$sql .= " and (g.name like '%s' or g.py like '%s')";
			$queryParams[] = "%{$name}%";
			$queryParams[] = "%{$name}%";
		}
		if ($spec) {
			$sql .= " and (g.spec like '%s')";
			$queryParams[] = "%{$spec}%";
		}
		
		$data = $db->query($sql, $queryParams);
		$cnt = $data[0]["cnt"];
		
		return array(
				"dataList" => $result,
				"totalCount" => $cnt
		);
	}
	
	/**
	 * 提交货权转移单
	 * @param unknown $id
	 * @param unknown $module	整型 1 = 销售入库，2 = 采购入库
	 * @return boolean[]|string[]|boolean[]|string[]
	 */
	public function commitGOBill($id,$module) {
		if ($this->isNotOnline()) {
			return $this->notOnlineError();
		}
	
		$db = M();
		$db->startTrans();
	
		$bs = new BizConfigService();
		
		$ref_type = null;
		$sql = null;
		
		switch ($module) {
			case 1:			//销售出库	
				$ref_type = "销售出库"; 
				$sql = "select 
						a.id,
						a.bill_status,
						a.bizdt,
						a.biz_user_id,
						a.goodsowner_id as from_goodsowner_id,
						a.goodsowner_id as to_goodsowner_id,
						a.date_created,
						a.input_user_id,
						b.goods_id,
						b.goods_count,
						a.warehouse_id,
						a.data_org,
						a.company_id,
						a.ref
					from t_ws_bill a, t_ws_bill_detail b 
					where a.id = b.wsbill_id and a.id = '%s' ";
			break;
			
			case 2:	  //采购入库
				$ref_type = "采购入库"; 
				$sql = "select 
							a.id,
							a.bill_status,
							a.biz_dt as bizdt,
							a.biz_user_id,
							a.goodsowner_id as from_goodsowner_id,
							a.goodsowner_id as to_goodsowner_id,
							a.date_created,
							a.input_user_id,
							b.goods_id,
							b.goods_count,
							a.warehouse_id,
							a.data_org,
							a.company_id,
							a.ref
						from t_pw_bill a, t_pw_bill_detail b 
						where a.id = b.pwbill_id and a.id = '%s' ";
			break;
			
			case 3:	  //采购退货出库
				$ref_type = "采购退货出库"; 
				$sql = "select 
							a.id,
							a.bill_status,
							a.bizdt,
							a.biz_user_id,
							a.goodsowner_id as from_goodsowner_id,
							a.goodsowner_id as to_goodsowner_id,
							a.date_created,
							a.input_user_id,
							b.goods_id,
							b.rejection_goods_count as goods_count,
							a.warehouse_id,
							a.data_org,
							a.company_id,
							a.ref
						from t_pr_bill a, t_pr_bill_detail b 
						where a.id = b.prbill_id 
						      and a.id = '%s'
							  and b.rejection_goods_count > 0 ";
			break;
			
			case 4:	  //销售退货入库
				$ref_type = "销售退货入库";
				$sql = "select
							a.id,
							a.bill_status,
							a.bizdt,
							a.biz_user_id,
							a.goodsowner_id as from_goodsowner_id,
							a.goodsowner_id as to_goodsowner_id,
							a.date_created,
							a.input_user_id,
							b.goods_id,
							b.rejection_goods_count as goods_count,
							a.warehouse_id,
							a.data_org,
							a.company_id,
							a.ref
						from t_sr_bill a, t_sr_bill_detail b
						where a.id = b.srbill_id
						      and a.id = '%s'
							  and b.rejection_goods_count > 0 ";
				break;
				
			default:
				;
			break;
		}
		
		$data = $db->query($sql, $id);
		if (! data) {
			$db->rollback();
			return $this->bad("要提交的货权转移单不存在");
		}
		
		foreach ($data as $i => $v) {
			$ref = $data[$i]["ref"];
			$bizdt = $data[$i]["bizdt"];
			$dateCreated = $data[$i]["date_created"];
			$billStatus = $data[$i]["bill_status"];
			$bizUserId = $data[$i]["biz_user_id"];
			$goodsId = $data[$i]["goods_id"];
			$goodsCount = floatval($data[$i]["goods_count"]);
			$fromGoodsowneId = $data[$i]["from_goodsowner_id"];
			$warehouseId = $data[$i]["warehouse_id"];
			$dataOrg = $data[$i]["data_org"];
			$toGoodsownerId = $data[$i]["to_goodsowner_id"];
			$companyId = $data[$i]["company_id"];
		
			if ($billStatus != 0) {
				$db->rollback();
				return $this->bad("货权转移单已经提交，不能再次提交");
			}
		
			$sql = "select name as cnt from t_user where id = '%s' ";
			$dataTmp = $db->query($sql, $bizUserId);
			if (! $data) {
				$db->rollback();
				return $this->bad("业务员不存在");
			}
		
			$sql = "select code, name from t_goods where id = '%s' ";
			$dataTmp = $db->query($sql, $goodsId);
			if (! $dataTmp) {
				$db->rollback();
				return $this->bad("要转移的商品不存在(商品后台id = {$goodsId})");
			}
			$goodsCode = $dataTmp[0]["code"];
			$goodsName = $dataTmp[0]["name"];
			if ($goodsCount <= 0) {
				$db->rollback();
				return $this->bad("商品[{$goodsCode} {$goodsName}]的转移数量需要是正数");
			}
					
			if($module == 2 || $module == 4) {
				/*****************************下面分为两部分，一是转入部分*************************************/
				// 货权总账
				$sql = "select
							id,
							goodsowner_id,
							balance_count,
							goods_id,
							in_count,
							out_count,
							warehouse_id,
							data_org,
							company_id
						from t_goodsowner_inventory
						where
							goods_id = '%s' and goodsowner_id = '%s'";
			
				$inventoryData = $db->query($sql, $goodsId, $toGoodsownerId);
				if ($inventoryData === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			
				if($inventoryData) { //如果存在更新
			
					$invId = $inventoryData[0]["id"];
					//插入货主转出信息
					$invBalanceCount = $inventoryData[0]["balance_count"] + $goodsCount;
					$invInCount = $inventoryData[0]["in_count"] + $goodsCount;
			
					$sql = "update t_goodsowner_inventory
								set balance_count = '%s',
									in_count = '%s'
								where id = '%s'";
			
					$inventoryData = $db->execute($sql, $invBalanceCount, $invInCount, $invId);
					if ($inventoryData === false) {
						$db->rollback();
						return $this->sqlError(__LINE__);
					}
				} else { //如果不存在则插入
					$sql = "insert into t_goodsowner_inventory(
								goodsowner_id,
								balance_count,
								goods_id,
								out_count,
								in_count,
								warehouse_id,
								company_id) values (
									'%s',
									'%f',
									'%s',
									'%f',
									'%f',
									'%s',
									'%s'
								)";
					$inventoryData = $db->execute($sql,$toGoodsownerId,$goodsCount,$goodsId,0,$goodsCount,$warehouseId,$companyId);
					if ($inventoryData === false) {
						$db->rollback();
						return $this->sqlError(__LINE__);
					}
				}
			
				// 库存明细账
				$sql = "insert into t_goodsowner_inventory_detail(
							goodsowner_id,
							biz_goodsowner_id,
							balance_count,
							biz_date,
							biz_user_id,
							date_created,
							goods_id,
							in_count,
							out_count,
							ref_number,
							ref_type,
							warehouse_id,
							data_org,
							company_id)
						values (
							'%s',
							'%s',
							'%f',
							'%s',
							'%s',
							'%s',
							'%s',
							'%f',
							'%f',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s'
						)";
				$inventoryData = $db->execute($sql,
						$toGoodsownerId,
						$fromGoodsowneId,
						$goodsCount,
						$bizdt,
						$bizUserId,
						$dateCreated,
						$goodsId,
						$goodsCount,
						0,
						$ref,
						$ref_type,
						$warehouseId,
						$dataOrg,
						$companyId);
				if ($inventoryData === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			}
			
		
			if($module == 1 || $module == 3) {
				/*****************************下面分为两部分，二是转出部分*************************************/
				// 货权总账
				$sql = "select
							id,
							goodsowner_id,
							balance_count,
							goods_id,
							in_count,
							out_count,
							warehouse_id,
							data_org,
							company_id
						from t_goodsowner_inventory
						where
							goods_id = '%s' and goodsowner_id = '%s'";
			
				$inventoryData = $db->query($sql, $goodsId, $fromGoodsowneId);
				if ($inventoryData === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			
				if($inventoryData) { //如果存在更新
			
					$invId = $inventoryData[0]["id"];
					//插入货主转出信息
					$invBalanceCount = $inventoryData[0]["balance_count"] - $goodsCount;
					$invOutCount = $inventoryData[0]["out_count"] + $goodsCount;
						
					$sql = "update t_goodsowner_inventory
								set balance_count = '%s',
									out_count = '%s'
								where id = '%s'";
						
					$inventoryData = $db->execute($sql, $invBalanceCount, $invOutCount, $invId);
					if ($inventoryData === false) {
						$db->rollback();
						return $this->sqlError(__LINE__);
					}
				} else { //如果不存在则插入
					$sql = "insert into t_goodsowner_inventory(
								goodsowner_id,
								balance_count,
								goods_id,
								out_count,
								in_count,
								warehouse_id,
								company_id) values (
									'%s',
									'%f',
									'%s',
									'%f',
									'%f',
									'%s',
									'%s'
								)";
					$inventoryData = $db->execute($sql,$fromGoodsowneId,-$goodsCount,$goodsId,$goodsCount,0,$warehouseId,$companyId);
					if ($inventoryData === false) {
						$db->rollback();
						return $this->sqlError(__LINE__);
					}
				}
			
				// 库存明细账
				$sql = "insert into t_goodsowner_inventory_detail(
							goodsowner_id,
							biz_goodsowner_id,
							balance_count,
							biz_date,
							biz_user_id,
							date_created,
							goods_id,
							in_count,
							out_count,
							ref_number,
							ref_type,
							warehouse_id,
							data_org,
							company_id)
						values (
							'%s',
							'%s',
							'%f',
							'%s',
							'%s',
							'%s',
							'%s',
							'%f',
							'%f',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s'
						)";
				$inventoryData = $db->execute($sql,    $fromGoodsowneId,
						$toGoodsownerId,
						$goodsCount,
						$bizdt,
						$bizUserId,
						$dateCreated,
						$goodsId,
						0,
						$goodsCount,
						$ref,
						$ref_type,
						$warehouseId,
						$dataOrg,
						$companyId);
				if ($inventoryData === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			}
		}
		
	
		$sql = "update t_goodsowner_bills
					set bill_status = 1000
					where id = '%s' ";
		$inventoryData = $db->execute($sql, $id);
		if ($inventoryData === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
	
		$log = "提交货权转移单，单号 = {$ref}";
		$bs = new BizlogService();
		$bs->insertBizlog($log, $this->LOG_CATEGORY);
	
		$db->commit();
	
		return $this->ok($id);
	}
}